<template>
  <div class="comment-page">
    <div class="comment-list">
      <!-- 暂无评论提示 -->
      <div v-if="comments.length === 0" class="no-comments">
        暂无评论，快来抢沙发吧~
      </div>

      <!-- 评论列表 -->
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <div class="comment-header">
          <img
              :src="comment.avatarUrl"
              class="user-avatar"
              style="width: 40px; height: 40px; border-radius: 50%;"
          />
          <div class="user-meta">
            <div class="username">{{ comment.userName || '未知用户' }}</div>
            <div class="time">{{ formatTime(comment.createTime) || '未知时间' }}</div>
          </div>
        </div>
        <div class="comment-content">
          {{ comment.content || '无内容' }}
        </div>
      </div>
    </div>
    <!-- 评论输入框和按钮 -->
    <div class="comment-input-bar">
      <input
          v-model="newComment"
          placeholder="写下你的评论..."
          class="input-field"
          @keyup.enter="handleSubmitComment"
      />
      <button
          class="submit-button"
          @click="handleSubmitComment"
      >评论</button>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {useRoute} from 'vue-router';
import {Toast} from 'vant';
import myAxios from "../../plugins/myAxios.ts";

const route = useRoute();
const comments = ref([]);
const newComment = ref('');

// 加载评论列表
const loadComments = async () => {
  try {
    const res = await myAxios.get('/post/comment', {
      params: {
        postId: route.params.postId
      }
    });

    console.log("API Response:", res); // 打印完整响应

    // 如果 res.data 是字符串，先解析为对象或数组
    const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;

    console.log("Comments Data:", JSON.stringify(data, null, 2)); // 打印格式化后的评论数据

    // 处理 null 数据
    comments.value = data || [];

    if (res.code !== 0) {
      Toast.fail('加载评论失败');
    }
  } catch (error) {
    console.error("请求失败:", error);
    Toast.fail('网络错误：' + error.message);
  }
};

// 时间格式化
const formatTime = (timeStr) => {
  try {
    if (!timeStr) return "未知时间";

    // 手动解析时间字符串
    const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
    const match = timeStr.match(regex);

    if (!match) {
      console.error("时间格式不正确:", timeStr);
      return "未知时间";
    }

    const [year, month, day, hours, minutes, seconds] = match.slice(1);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error("时间格式化错误:", error);
    return "未知时间";
  }
};

// 提交评论
const handleSubmitComment = async () => {
  // 校验输入
  if (!newComment.value.trim()) {
    return Toast('评论内容不能为空');
  }

  // 获取当前用户
  const currentUserId = localStorage.getItem("userId");
  if (!currentUserId) {
    return Toast('请先登录');
  }

  try {
    const res = await myAxios.post('/post/addComment', {
      userId: currentUserId,
      postId: route.params.postId,
      content: newComment.value.trim()
    });

    if (res.code === 0) {
      Toast.success('评论成功');
      newComment.value = ''; // 清空输入框
      await loadComments();  // 重新加载评论列表
    } else {
      Toast.fail(res.message || '评论失败');
    }
  } catch (error) {
    Toast.fail(`提交失败：${error.message}`);
  }
};

// 初始化加载
onMounted(() => {
  loadComments();
});
</script>

<style scoped>
.comment-page {
  padding: 16px;
  padding-bottom: 80px; /* 给底部输入栏留出空间 */
}

.comment-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f8f8;
  border-radius: 8px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.user-avatar {
  margin-right: 12px;
}

.user-meta {
  flex: 1;
}

.username {
  font-weight: bold;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #666;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
  padding-left: 52px;
}

.no-comments {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 22px;
}

.comment-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.input-field {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 18px;
  font-size: 14px;
}

.submit-button {
  padding: 8px 16px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 18px;
  font-size: 14px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #06ad56;
}
</style>
